#ifndef ____UDP_HPP____
#define ____UDP_HPP____
#include <unistd.h>
#include <iostream>
#include <string>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <functional>
#include "Addr.hpp"

using func_t = std::function<void(int _sockfd, const std::string message, Inet_Addr _addr)>;

class ChatServer
{
public:
    ChatServer(uint16_t port, func_t func)
        : _port(port), _socketfd(-1), _isrunning(false), _func(func)
    {
    }

    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            perror("socket");
            exit(1);
        }
        Inet_Addr _siny(_port);
        int n = bind(_socketfd, _siny.Addr(), _siny.Size());
        if (n < 0)
        {
            perror("bind");
            exit(1);
        }
    }

    void Start()
    {
        if (_isrunning)
            return;
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024] = {0};
            struct sockaddr_in _sender;
            memset(&_sender, 0, sizeof(_sender));
            socklen_t len = sizeof(_sender);
            ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&_sender, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                // std::cout << buffer << std::endl;
                Inet_Addr Client(_sender);
                std::string message = buffer;
                _func(_socketfd, message, Client);
            }
        }
        _isrunning = false;
    }

    void Stop()
    {
        _isrunning = false;
    }

    ~ChatServer()
    {
    }

private:
    func_t _func;
    uint16_t _port;
    int _socketfd;
    bool _isrunning;
};

#endif